import Mock from 'mockjs'

import routes from '@/router/views'

function filterMenu (routes) {
  const res = []

  for (const route of routes) {
    const menu = {
      path: route.path,
      name: route.name,
      meta: route.meta
    }

    const hasChildren = route.children && route.children.length > 0

    if (hasChildren) menu.children = filterMenu(route.children)

    res.push(menu)
  }
  return res
}

const mocks = [
  {
    url: 'login',
    type: 'post',
    response: {
      code: 200,
      data: {
        token: '2021091623572501021220208754C34903'
      }
    }
  },
  {
    url: 'userinfo',
    type: 'post',
    response: {
      code: 200,
      data: {
        userName: 'admin',
        userPortrait: 'https://img0.baidu.com/it/u=1077360284,2857506492&fm=26&fmt=auto',
        roles: ['admin']
      }
    }
  },
  {
    url: 'menu',
    type: 'post',
    response: {
      code: 200,
      data: filterMenu(routes)
    }
  }
]

function mockXHR () {
  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type, i.response)
  }
}

export {
  mockXHR
}
